package com.zw.web.oss.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSException;
import com.zw.web.oss.config.OssConfigProperties;
import com.zw.web.oss.service.FileUploadService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

/**
 * 文件覆盖的问题
 * 添加目录  唯一性
 * 重命名
 */
@Service
public class FileUploadServiceImpl implements FileUploadService {
    public static final String OSS_IMAGE_PREFIX = "images/";
    @Resource
    private OSS oss;
    @Resource
    private OssConfigProperties ossConfigProperties;

    @Override
    public String upload(MultipartFile multipartFile) {
        /*
         * 上传文件的 bucketName
         * 文件上传的路径和名字
         *  images/20240118/20240118114000.png
         */
        String key = String.format("%s%s", getFilePath(), getFileName(multipartFile.getOriginalFilename()));
        try {
            InputStream inputStream = multipartFile.getInputStream();
            oss.putObject(ossConfigProperties.getBucketName(), key, inputStream);
        } catch (OSSException | ClientException | IOException e) {
            throw new RuntimeException(e);
        }
        return ossConfigProperties.getDoMain() + key;
    }

    /**
     * 1111.png
     */
    private String getFileName(String oldFileName) {
        //获取文件的格式
        return String.format("%s%s%s", DateUtil.format(new Date(), "yyyyMMddHHmmss"), RandomUtil.randomNumbers(4), oldFileName.substring(oldFileName.lastIndexOf(".")));
    }

    private String getFilePath() {
        return String.format("%s%s", OSS_IMAGE_PREFIX, DateUtil.format(new Date(), "yyyyMMdd") + "/");
    }

}
